package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.entity.TokenEntity;
import one.stand.entity.WxNoticeEntity;
import one.stand.enums.LoginEnum;
import one.stand.enums.SendTypeEnum;
import one.stand.enums.WxNoticeEnums;
import one.stand.model.*;
import one.stand.request.RoyaltyRecordRequest;
import one.stand.request.UserCommonRequest;
import one.stand.request.UserLevelRequest;
import one.stand.request.UserRequest;
import one.stand.response.OrdersResponse;
import one.stand.response.RoyaltyRecordResponse;
import one.stand.response.UserCommonResponse;
import one.stand.response.UserResponse;
import one.stand.service.BaseService;
import one.stand.service.UserService;
import one.stand.service.WxMessageService;
import one.stand.service.WxPayService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
public class UserServiceImpl extends BaseService implements UserService {
    @Autowired
    private WxMessageService wxMessageService;


    @Override
    public ResultModel addUser(UserRequest model, TokenEntity tokenEntity) {
        model.setUserId(tokenEntity.getId());
        UserModel userModel = new UserModel();
        BeanUtils.copyProperties(model,userModel);
        r = userMapper.updateByPrimaryKeySelective(userModel);
        if(r > 0) {
            return  ResultModel.success("保存成功");
        }
        return  ResultModel.fail();
    }

    @Override
    public ResultModel<UserResponse> getUserList(TokenEntity tokenEntity) {
        UserModel outModel = userMapper.selectByPrimaryKey(tokenEntity.getId().intValue());
        if(outModel == null){
            return ResultModel.noData();
        }
        UserResponse userResponse = new UserResponse();
        BeanUtils.copyProperties(outModel,userResponse);
        return  ResultModel.success(userResponse);
    }



    @Override
    public ResultModel<Integer> addFormId(UserRequest request){
        if(request == null || request.getId() == null || request.getType() == null){
            return ResultModel.checkParamFail();
        }
        Map<String, String> map = new HashMap<>(3);
        map.put("userId",request.getId().toString());
        map.put("type",request.getType().toString());
        Integer num = userMapper.formIdCount(map);
        map.put("formId",request.getFormId());
        userMapper.addFormId(map);
        return ResultModel.success(num + 1);
    }

    /**
     * 发送给crm端的员工
     *
     * @param sendUserId 发送人userId
     * @param text 聊天消息提示內容
     * @param type 0未读消息提示，1联系方式提示
     * @return
     */
    @Override
    public ResultModel unreadMessage(Integer sendUserId, Integer receiveUserId, String text, Integer type){
        // 微信推送 未读消息
        WxNoticeEntity entity = userMapper.getSendTemplateInfo(sendUserId,receiveUserId,1);
        if(type.equals(SendTypeEnum.CONTACT_US.getCode())){
            text = "已向你发送了联系方式，尽快与他联系~!";
        }
        String[] arr = {entity.getNickeName(),getDay(),text};
        wxMessageService.sendTemplate(entity.getCrmOpenId(), entity.getCrmFormId(), WxNoticeEnums.UNREAD_MESSAGE.getCode(), arr, LoginEnum.CRM.getAccountType(),entity.getCompanyId());
        return ResultModel.success();
    }

    @Override
    public ResultModel<Map<String, Object>> selectRoyaltyRecord(RoyaltyRecordRequest request) {
        if(request == null || request.getType() == null){
            return ResultModel.checkParamFail();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<RoyaltyRecordModel> list = royaltyRecordMapper.select(new RoyaltyRecordModel(){{
            setType(request.getType());
            setUserId(request.getId().intValue());
        }});
        if(list == null || list.size() <= 0){
            return ResultModel.noData();
        }
        List<RoyaltyRecordResponse> royaltyRecordResponses = new ArrayList<>();
        list.forEach(obj -> {
            {
                RoyaltyRecordResponse royaltyRecordResponse = new RoyaltyRecordResponse();
                BeanUtils.copyProperties(obj, royaltyRecordResponse);
                royaltyRecordResponses.add(royaltyRecordResponse);
            }
        });
        PageInfo<RoyaltyRecordResponse> pageInfo = new PageInfo<>(royaltyRecordResponses);
        Map<String, Object> map = new HashMap<>(3);
        map.put("list", JSON.toJSONString(pageInfo.getList()));
        map.put("total",pageInfo.getTotal());
        map.put("allMoney",royaltyRecordMapper.selectAllMoney(new RoyaltyRecordModel(){{
            setType(request.getType());
            setUserId(request.getId().intValue());
        }}));
        return ResultModel.success(map);
    }

    @Autowired
    WxPayService wxPayService;

    @Override
    public ResultModel<Boolean> doCash(RoyaltyRecordRequest request) {
        if(request == null){
            return ResultModel.checkParamFail();
        }
        try {
            //微信提现申请
            ResultModel resultModel = wxPayService.doCash("","",request.getRoyaltyMoney(),"",request.getCompanyKey());
            if(resultModel.isSuccess()) {
                // 操作成功
                RoyaltyRecordModel model = new RoyaltyRecordModel();
                model.setUserId(request.getId().intValue());
                model.setRoyaltyMoney(request.getRoyaltyMoney());
                model.setType(2);
                model.setCreateTime(currentDate());
                model.setIsDel(0);
                royaltyRecordMapper.insertSelective(model);
            }
            return resultModel;
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel<List<UserCommonResponse>> selectUserCommonList(UserCommonRequest request) {
        log.info("查询用户常用语:{}",JSON.toJSONString(request));
        if(request == null || request.getId() == null){
            return ResultModel.checkParamFail();
        }
        UserCommonModel model = new UserCommonModel();
        model.setType(1);
        model.setUserId(request.getId().intValue());
        List<UserCommonModel> list = userCommonMapper.select(model);
        if(list == null || list.size() <= 0){
            return ResultModel.noData();
        }
        List<UserCommonResponse> responseList = new ArrayList<>();
        list.forEach(obj->{{
            UserCommonResponse response = new UserCommonResponse();
            BeanUtils.copyProperties(obj, response);
            responseList.add(response);
        }});
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel<Boolean> insertUserCommonList(UserCommonRequest request) {
        log.info("新增/修改用户常用语:{}",JSON.toJSONString(request));
        if(request == null || request.getId() == null || StringUtils.isBlank(request.getText())){
            return ResultModel.checkParamFail();
        }
        if(userCommonMapper.selectCount(new UserCommonModel(){{setUserId(request.getId().intValue()); setType(1);}}) > 12){
            return ResultModel.fail("常用语不能超过12条~！");
        }
        UserCommonModel model = new UserCommonModel();
        model.setText(request.getText());
        if(request.getCommonId() == null) {
            model.setType(1);
            model.setUserId(request.getId().intValue());
            model.setIsDel(0);
            model.setSort(userCommonMapper.getMaxSort(new UserCommonModel(){{ setUserId(request.getId().intValue()); setType(1);}}) + 1);
            model.setCreateTime(currentDate());
            userCommonMapper.insertSelective(model);
            return ResultModel.success(true);
        }
        model.setCommonId(request.getCommonId());
        userCommonMapper.updateByPrimaryKeySelective(model);
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<Boolean> delUserCommonList(UserCommonRequest request) {
        log.info("删除用户常用语:{}",JSON.toJSONString(request));
        if(request == null || request.getCommonId() == null){
            return ResultModel.checkParamFail();
        }
        UserCommonModel model = new UserCommonModel();
        model.setIsDel(1);
        model.setCommonId(request.getCommonId());
        userCommonMapper.updateByPrimaryKeySelective(model);
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<Boolean> moveUserCommon(UserCommonRequest request) {
        if(request == null || request.getCommonId() == null || request.getMoveType() == null || request.getId() == null){
            return ResultModel.checkParamFail();
        }
        UserCommonModel model = new UserCommonModel();
        model.setCommonId(request.getCommonId());
        model.setMoveType(request.getMoveType());
        model.setType(1);
        model.setUserId(request.getId().intValue());
        UserCommonModel userCommonModel = userCommonMapper.selectThanSort(model);
        if(userCommonModel == null){
            if(ONE.equals(request.getMoveType())){
                return ResultModel.fail("到顶了，无法上移！");
            }else if(TWO.equals(request.getMoveType())){
                return ResultModel.fail("到底了，无法下移！");
            }
        }
        // 修改排序
        model.setSort(userCommonModel.getSort());
        if(userCommonMapper.updateByPrimaryKeySelective(model) > 0){
            model = new UserCommonModel();
            model.setCommonId(userCommonModel.getCommonId());
            model.setSort(userCommonModel.getLastSort());
            userCommonMapper.updateByPrimaryKeySelective(model);
            return ResultModel.success(true);
        }
        return ResultModel.fail();
    }
}
